package com.emperor.course.app;

import java.text.DecimalFormat;
import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;

import com.emperor.cashier.app.CashierAppCtrl;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.course.logic.Course;
import com.emperor.course.logic.CourseProduct;
import com.emperor.customer.app.CustomerAppCtrl;
import com.emperor.product.logic.Product;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;

public class CourseProdAppEnq extends AppBase implements App {

	protected Shell shlSearchCourseProducts;
	public static Logger log = Logger.getLogger(CourseProdAppEnq.class);

	public CourseProdAppEnq() {
		super();
	}

	public CourseProdAppEnq(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CourseProdAppEnq window = new CourseProdAppEnq();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shlSearchCourseProducts.open();
		shlSearchCourseProducts.layout();
		while (!shlSearchCourseProducts.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shlSearchCourseProducts = new Shell();
		shlSearchCourseProducts.setBackgroundImage(SWTResourceManager.getImage(
				CourseProdAppEnq.class, "/img/main.jpg"));
		shlSearchCourseProducts.setImage(SWTResourceManager.getImage(CourseProdAppEnq.class,
				"/img/iMac OSX.png"));
		shlSearchCourseProducts.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		shlSearchCourseProducts.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shlSearchCourseProducts.setSize(1280, 800);
		shlSearchCourseProducts.setText("Search Course Products");

		initScreen(shlSearchCourseProducts, getParams());

		final Composite composite = new Composite(shlSearchCourseProducts, SWT.NONE);
		composite.setBounds(0, 50, 892, 83);

		final Label productNameLabel = new Label(composite, SWT.NONE);
		productNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		productNameLabel.setText("Product Name");
		productNameLabel.setBounds(10, 47, 120, 20);

		final Text text = new Text(composite, SWT.BORDER);
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		text.setToolTipText("name");
		text.setBounds(134, 44, 282, 30);

		final Table table = new Table(shlSearchCourseProducts, SWT.FULL_SELECTION | SWT.BORDER);
		table.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		table.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(final MouseEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i = 0; i < items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							Product product = (Product) item.getData();
							Long courseId = (Long) getParams().get(
									CourseAppCtrl.COURSE_ID);

							getParams().put(CourseAppCtrl.PROD_ID,
									product.getId());
							getParams().put(CourseAppCtrl.COURSE_ID, courseId);

							CourseProdAppNew dialog = new CourseProdAppNew(
									getShell(), SWT.ICON_INFORMATION,
									getParams());
							dialog.open();
						}
					}
				}
			}
		});
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		table.setBounds(10, 139, 1252, 438);

		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		messageLabel.setText("Please key in the employee name to search.");
		messageLabel.setBounds(11, 10, 871, 20);

		final Button searchButton = new Button(composite, SWT.NONE);
		searchButton.setImage(SWTResourceManager.getImage(
				CourseProdAppEnq.class, "/img/Zoom-in.png"));
		searchButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		searchButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				populateTable(table, text, messageLabel);
			}
		});
		searchButton.setText("Search");
		searchButton.setBounds(422, 42, 90, 30);

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.setWidth(64);
		newColumnTableColumn.setText("No.");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(397);
		newColumnTableColumn_1.setText("Name");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(211);
		newColumnTableColumn_2.setText("SKU");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_3.setWidth(261);
		newColumnTableColumn_3.setText("Price");

		final Button addNewEmployeButton = new Button(shlSearchCourseProducts, SWT.NONE);
		addNewEmployeButton.setVisible(false);
		addNewEmployeButton.setImage(SWTResourceManager.getImage(
				CourseProdAppEnq.class, "/img/Symbol-Add.png"));
		addNewEmployeButton.setFont(SWTResourceManager
				.getFont("", 12, SWT.NONE));
		addNewEmployeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getParams().put(AppConstant.APPCTRL, CourseAppCtrl.COURSE_CTRL);
				getParams().put(AppConstant.ACTION, CourseAppCtrl.COURSE_NEW);
				getShell().close();
			}
		});
		addNewEmployeButton.setText("Add");
		addNewEmployeButton.setBounds(10, 687, 65, 30);
		//
		buildStandardMenu(getShell(), getParams(), CourseAppCtrl.COURSE_CTRL,
				CourseAppCtrl.COURSE_MGM);
		populateTable(table, text, messageLabel);

		TableColumn newColumnTableColumn_4 = new TableColumn(table, SWT.NONE);
		newColumnTableColumn_4.setWidth(261);
		newColumnTableColumn_4.setText("Quantity");
		populateMsg(messageLabel);

		final Button updateEmployeeButton = new Button(shlSearchCourseProducts, SWT.NONE);
		updateEmployeeButton.setVisible(false);
		updateEmployeeButton.setImage(SWTResourceManager.getImage(
				CourseProdAppEnq.class, "/img/Edit.png"));
		updateEmployeeButton.setFont(SWTResourceManager.getFont("", 12,
				SWT.NONE));
		updateEmployeeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				TableItem[] items = table.getSelection();
				if (items != null && items.length > 0) {
					for (int i = 0; i < items.length; i++) {
						TableItem item = items[i];
						if (item.getData() != null) {
							Course course = (Course) item.getData();
							getParams().put(CourseAppCtrl.COURSE_ID,
									course.getId());

							getParams().put(AppConstant.APPCTRL,
									CourseAppCtrl.COURSE_CTRL);
							getParams().put(AppConstant.ACTION,
									CourseAppCtrl.COURSE_MGM);
							getShell().close();
						}
					}
				}
			}
		});
		updateEmployeeButton.setText("Update");
		updateEmployeeButton.setBounds(81, 687, 90, 30);

		final Button deleteButton = new Button(shlSearchCourseProducts, SWT.NONE);
		deleteButton.setImage(SWTResourceManager.getImage(
				CourseProdAppEnq.class, "/img/Symbol-Delete.png"));
		deleteButton.setBounds(177, 687, 85, 30);
		deleteButton.setFont(SWTResourceManager.getFont("", 12, SWT.NONE));
		deleteButton.setText("Delete");
		deleteButton.setVisible(false);
	}

	public Shell getShell() {
		return shlSearchCourseProducts;
	}

	public void setShell(Shell shell) {
		this.shlSearchCourseProducts = shell;
	}

	public void populateTable(Table table, Text text, Label label) {
		StringBuffer sb = new StringBuffer();
		table.clearAll();
		table.removeAll();
		table.redraw();
		int count = 0;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			String name = text.getText();
			session.beginTransaction();
			// TODO Replace with StringUtills
			List<Product> products = new ArrayList<Product>();

			Criteria cris = session.createCriteria(Product.class);

			if (name != null && !StringUtils.isEmpty(name)) {
				cris.add(Restrictions.like(Product.FLD_NAME, "%" + name + "%"));
			}
			products = cris.list();

			DecimalFormat df0 = new DecimalFormat();
			df0.applyPattern("##########.##");
			df0.setMinimumFractionDigits(0);
			df0.setMaximumFractionDigits(0);

			for (Iterator<Product> iter = products.iterator(); iter.hasNext();) {
				Product product = iter.next();
				count++;
				TableItem item = new TableItem(table, SWT.BORDER);
				item.setText(new String[] { count + ".", product.getName(),
						product.getSku(), df0.format(product.getPrice()),
						Double.toString(product.getQuantity()) });
				item.setData(product);
			}
			sb.append(count).append(" product(s) found.");
		} catch (Exception e) {
			sb.append("No result found. [").append(e.getMessage()).append("]");
			log.error(sb.toString(), e);
		}
		label.setText(sb.toString());
	}

	private void populateMsg(Label label) {
		try {
			if (getParams().get(CourseAppCtrl.COURSE_MSG) != null) {
				String msg = (String) getParams().get(CourseAppCtrl.COURSE_MSG);
				label.setText(msg);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
